home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 13388 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.2 KB  |  64 lines

  1. Path: mail2news.demon.co.uk!genesis.demon.co.uk
  2. From: Lawrence Kirby <fred@genesis.demon.co.uk>
  3. Newsgroups: comp.lang.c,comp.unix.programmer
  4. Subject: Re: Q: '\n' character - strtok trick
  5. Date: Sat, 06 Apr 96 15:11:45 GMT
  6. Organization: none
  7. Message-ID: <828803505snz@genesis.demon.co.uk>
  8. References: <31616F63.481D@lava.weeg.uiowa.edu> <828493319snz@genesis.demon.co.uk> <828542474.7672@tertio.demon.co.uk> <4ju9m0$nq9@belle.bork.com> <4k1jmd$ifr@sun001.spd.dsccc.com>
  9. Reply-To: fred@genesis.demon.co.uk
  10. X-NNTP-Posting-Host: genesis.demon.co.uk
  11. X-Newsreader: Demon Internet Simple News v1.27
  12. X-Mail2News-Path: genesis.demon.co.uk
  13.  
  14. In article <4k1jmd$ifr@sun001.spd.dsccc.com>
  15.            jmccarty@sun1307.spd.dsccc.com "Mike McCarty" writes:
  16.  
  17. >I usually do this (from memory only, so argument order etc. may be off):
  18. >
  19. >        boolean readline(char *buffer,size_t max_size,FILE *stream) {
  20. >                boolean result;
  21. >                size_t  place;
  22. >
  23. >                if (fgets(buffer,max_size,stream) == NULL)
  24. >                        result = false;
  25. >                else {
  26. >                        place = strlen(buffer)-1;
  27. >                        if (place >= 0 && buffer[place] == '\n')
  28.  
  29. Since size_t is an unsigned type place >= 0 will always be true.
  30.  
  31. >                                buffer[place] = '\0';
  32. >                        result = true;
  33. >                }
  34. >                return result;
  35. >        }
  36.  
  37. If you maintain the form of fgets() you could use this as a drop-in
  38. replacement. I see no advantage to introducing a boolean 'type'.
  39.  
  40. char *readline(char *buffer, int max_size, FILE *stream)
  41. {
  42.  
  43.     char *const result = fgets(buffer, max_size, stream);
  44.  
  45.     if (result != NULL) {
  46.         int place = strlen(result);
  47.  
  48.         if (place != 0 && result[--place] == '\n')
  49.             result[place] = '\0';
  50.     }
  51.  
  52.     return result;
  53. }
  54.  
  55. I used int rather than size_t since that is the limit on size imposed by
  56. fgets(), and the 2nd argument int makes clear that the function doesn't
  57. work with a buffer size greater than INT_MAX.
  58.  
  59. -- 
  60. -----------------------------------------
  61. Lawrence Kirby | fred@genesis.demon.co.uk
  62. Wilts, England | 70734.126@compuserve.com
  63. -----------------------------------------
  64.